from flask import Blueprint, render_template, request, jsonify, redirect, url_for
from werkzeug.security import generate_password_hash, check_password_hash

from apps.users.models import User
from exts import db

user_bp1 = Blueprint('user', __name__, url_prefix='/user')


@user_bp1.route('/')
def index():
    uid = request.cookies.get('uid',None)
    if uid:
        user
    return render_template('user/index.html')


# 用户注册
@user_bp1.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        if request.method == 'POST':
            username = request.form.get('username')
            password = request.form.get('password')
            repassword = request.form.get('repassword')
            phone = request.form.get('phone')
            email = request.form.get('email')
            if password == repassword:
                # 1、找到模型类并创建对象
                user = User()
                # 2.给对象的属性赋值
                user.username = username
                # 使用自带函数加密
                user.password = generate_password_hash(password)
                print(password)
                user.phone = phone
                user.email = email
                # 添加
                # 3.将user对象添加到SESSION中（类似缓存）
                db.session.add(user)
                # 4。提交数据
                db.session.commit()
                return render_template('user/index.html')
            else:
                return '两次输入的密码不一致'

    return render_template('user/register.html')


# 手机号码验证
@user_bp1.route('/checkphone', methods=['GET', 'POST'])
def check_phone():
    phone = request.args.get('phone')
    user = User.query.filter(User.phone == phone).all()
    if len(user) > 0:
        return jsonify(code=400, msg='此号码已被注册')
    else:
        return jsonify(code=200, msg='此号码可用')


# 用户登陆
@user_bp1.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        # 关键 select * from user where username='xxx'
        users = User.query.filter(User.username == username).all()
        for user in users:
            # 如果flag返回True表示匹配，否则密码不匹配
            flag = check_password_hash(user.password, password)
            if flag:
                response = redirect(url_for('user.index'))
                response.set_cookie('uid', str(user.id), max_age=1800)
                return response
        else:
            return render_template('user/login.html', msg='账户或密码错误')
    return render_template('user/login.html')
